/*
 * @Author: wfl
 * @LastEditors: wfl
 * @description: 
 * @updateInfo: 
 * @Date: 2020-12-08 14:50:40
 * @LastEditTime: 2020-12-08 16:21:29
 */
import SparkMD5 from 'spark-md5'
import { FileBlob, CHUNK_SIZE } from './index'
// 获取文件Md5值
const getFileChunkMd5 = (fileChunkList: FileBlob[]): Promise<string> => {
    return new Promise((resolve, reject) => {
        // 总切片数
        const chunkSize = fileChunkList.length;
        // 当前处理位置
        let currentChunk = 0;
        // SparkMD5实例的ArrayBuffer
        let spark = new SparkMD5.ArrayBuffer()
        let fileReader = new FileReader();
        fileReader.onload = (e: any) => {
            try {
                spark.append(e.target.result)
            } catch (error) {
                console.log('获取Md5错误，错误位置：' + currentChunk);
            }
            currentChunk++;

            if (currentChunk < chunkSize) {
                loadNext();
            } else {
                console.info('获取Md5完成');
                resolve(spark.end())
            }
        }
        fileReader.onerror = function () {
            console.warn('Md5：文件读取错误');
        };

        function loadNext() {
            fileReader.readAsArrayBuffer(fileChunkList[currentChunk].file);
        }
        loadNext();
    })
}

export default getFileChunkMd5
